package com.program.facesigninsystem.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;

/**
 * @author Mapler
 */
public class TokenUtil {

    /****
     * 默认为10天的token
     * @param uid 用户id
     * @param openid 开发平台id
     * @return 返回token字符串
     */
    public static String createToken(String uid,String openid){
        String token;
        token= JWT.create().withClaim("uid",uid)
                .withClaim("generatetime",System.currentTimeMillis())
                //设置token过期时间为10天
                .withClaim("exptime",1000*60*60*24*10)
                .sign(Algorithm.HMAC256(openid));
        return token;
    }

    /****
     * 自定义有效时长的token
     * @param uid 用户id
     * @param openid openid 开发平台id
     * @param liveTime token有效时长
     * @return 返回token字符串
     */
    public static String createToken(String uid,String openid,Long liveTime){
        String token;
        token= JWT.create().withClaim("uid",uid)
                .withClaim("generatetime",System.currentTimeMillis())
                //设置token过期时间为10天
                .withClaim("exptime",liveTime)
                .sign(Algorithm.HMAC256(openid));
        return token;
    }
    /****
     * 返回参数
     * @param token token字符串
     * @return 返回结果 true:token有效 false:token无效
     */
    public static boolean decodeToken(String token){
        Long currentTime = System.currentTimeMillis();
        try {
            Long generateTime = JWT.decode(token).getClaim("generatetime").asLong();
            Long expTime = JWT.decode(token).getClaim("exptime").asLong();
            return currentTime - generateTime <= expTime;
        }catch (Exception e){
            return true;
        }
    }
}
